import RemoteSelect from '@/components/RemoteSelect';

import { SUCCESS_CODE } from '@/utils/request';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';

import { getZoneSelectionList } from '@/pages/Zones/service';
import React, { useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import SpaceDetail from './components/SpaceDetail';
import SpaceOwnerUpdateForm from './components/SpaceOwnerUpdateForm';
import type { CreationItem, TableListItem } from './data';
import { addSpace, querySpaceList, removeSpace } from './service';

const TableList: React.FC = (props: any) => {
  const [sorter, setSorter] = useState<string>('');
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<string>();
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [spaceOwnerUpdateFormVisible, setSpaceOwnerUpdateFormVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // type  "public" "owner"
  const [type] = useState<string>(props?.match.params.type);
  const [operationItem, setOperationItem] = useState<TableListItem>();

  const handleAdd = async (fields: CreationItem) => {
    const hide = message.loading('正在添加');
    try {
      const res = await addSpace(fields);
      hide();
      if (res.code === SUCCESS_CODE) {
        message.success('添加成功');
        actionRef.current?.reload();
      } else {
        message.error(`添加失败！${res.message}`);
      }
      handleAddModalVisible(false);
    } catch (error) {
      hide();
      message.error('添加失败！未知的错误！');
      handleAddModalVisible(false);
    }
  };

  // 删除
  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await removeSpace(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  // @ts-ignore
  // @ts-ignore
  /**
   * 列表的列定义
   */
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '车位号',
      dataIndex: 'spaceName',
      render: (value) => <div>{value}</div>,
    },
    {
      title: '车场名称',
      dataIndex: 'zone',
      hideInTable: type != null && type === 'public',
      render: (_, record) => record.zone?.name || '',
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      renderFormItem: (_, {}) => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'id', value: 'id', label: 'name' }}
          request={(search) => getZoneSelectionList({ name: search })}
        />
      ),
    },
    {
      title: '绑定设备',
      dataIndex: 'device',
      hideInSearch: true,
      render: (_, record) => record?.device?.deviceName.toUpperCase() || '',
    },
    {
      title: '当前车辆',
      dataIndex: 'plateNumber',
      hideInSearch: true,
      render: (_, record) => <div>{record.plateNumber}</div>,
    },

    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: { text: '空闲', status: 'Success' },
        2: { text: '停车中', status: 'Processing' },
        3: { text: '已预约', status: 'Default' },
        4: { text: '未共享', status: 'Warning' },
      },
    },

    {
      title: '操作',
      dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setClickItemId(record.id);
        };

        const onClickRemove = () => {
          const { id, spaceName } = record;
          Modal.confirm({
            title: `删除停车位 ${id}`,
            content: (
              <>
                <Divider />
                <p>确认要删除停车位</p>
                <span style={{ fontWeight: 'bolder' }}>{spaceName}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
          });
        };

        return (
          <div>
            <a
              onClick={() => {
                setOperationItem(record);
                setSpaceOwnerUpdateFormVisible(true);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <a onClick={onClickDetail}>详情</a>
            <Divider type="vertical" />
            <a onClick={onClickRemove}>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="停车位列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          // <Button
          //   type="primary"
          //   onClick={() => {
          //     setSpaceOwnerUpdateFormVisible(true);
          //   }}
          // >
          //   <PlusOutlined /> 所有人信息绑定
          // </Button>,
          <Button type="primary" onClick={() => handleAddModalVisible(true)}>
            <PlusOutlined /> 添加
          </Button>,
        ]}
        tableAlertRender={() => false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return querySpaceList({ page, pageSize, ...filter, type: 'owner' });
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        onSubmit={(values: CreationItem) => handleAdd(values)}
        onCancel={() => handleAddModalVisible(false)}
        modalVisible={addModalVisible}
      />
      {!!operationItem && (
        <SpaceOwnerUpdateForm
          onCancel={() => {
            setSpaceOwnerUpdateFormVisible(false);
            setOperationItem(undefined);
          }}
          modalVisible={spaceOwnerUpdateFormVisible}
          onSubmit={async (success: boolean) => {
            if (success) {
              actionRef.current?.reload();
            }
            setOperationItem(undefined);
          }}
          item={operationItem}
        />
      )}
      <Drawer
        visible={!!clickItemId && detailVisible}
        onClose={() => setDetailVisible(false)}
        width="30%"
      >
        {!!clickItemId && detailVisible && <SpaceDetail id={clickItemId} />}
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TableList;
